<?php
if (!defined('HAPPY')) exit("Access Denied");
/**************************
@Author  : sulwan
@Content : 常用函数文件
**************************/
/**
 * 类自动加载
 *
 * @param string $className
 */
function __autoload($className){
	global $class_config;
	$className = strtolower($className);
	if ( isset($class_config[$className]) ){
		$classFile = $class_config[$className];
	}
	else {
		$classFile = 'unitl/'.$className.'.class.php';
	}
	if ( file_exists(dirname(__file__).'/./'.$classFile) ){
		include_once(dirname(__file__).'/./'.$classFile);
	}
}

/**
 * 取得对象实例 支持调用类的静态方法
 * @param string $className 对象类名
 * @param string $method 类的静态方法名
 * @param array  $args 参数数组
 * @return object
 */
function get_instance_of($className,$method='',$args=array()) {
    static $_instance = array();
	if( empty($args) ) {
		$identify =	$className.$method;
	}
	else{
		$identify =	$className.$method.to_guid_string($args);
	}
    if ( !isset($_instance[$identify]) ) {
        if( class_exists($className) ){
            $o = new $className();
            if( method_exists($o,$method) ){
                if( !empty($args) ) {
                	$_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
                }
                else {
                	$_instance[$identify] = $o->$method();
                }
            }
            else
                $_instance[$identify] = $o;
        }
        else{
        	exit('类不存在');
        }
    }
    return $_instance[$identify];
}

/**
 * Mysql转义
 *
 * @param string	 $str
 * @return string
 */
function mysql_escape($str){
	return mysql_escape_string($str);
}

/*设置缓存数据*/
function getCache($lunjing,$name,$caiji=0) {
	if(CACHE_OPEN||$caiji==1) {
		$path = $lunjing.$name.'.sulwan';
		if($caiji){
			if(file_exists($path)&&abs(filesize($filename))>1024) {
				return include($path);
			}
		}
		if(file_exists($path)&& time()-filemtime($path)<CACHE_LIFE) {
			return include($path);
		}
	}
	return 0;
}

/*获取缓存数据*/
function setCache($lunjing,$name,$tree,$caiji=0) {
	if(CACHE_OPEN||$caiji==1) {
		if(empty($name)) {
			return 0;
		}
		$path = $lunjing.$name.'.sulwan';
		mk_dir($lunjing);
		write_array_cache($tree,$path);
	}
}

/*删除缓存数据*/
function delCache($lunjing,$name='') {
	if(CACHE_OPEN) {
		if(empty($name)) {
			$path = $lunjing;
			clear_dir($path);
		}else{
			$path = $lunjing.$name.'.sulwan';
			@unlink($path);
		}
	}
}

/**
 *返回上级分类ID，以及分类路径
 */
function nameClassAndId($topic,$str=''){
	if(0 != $topic['pid']){
		$CataLog = new CataLog();
		$nameClassArray = $CataLog->lookRoleModule($topic['pid']);
		$str = $topic['typedir'].$str;
		return nameClassAndId($nameClassArray,$str);
	}else{
		$str = $topic['typedir'].$str.'/';
		$str = str_replace('\\', '/', $str);
		return $str;
	}
}

/**
 *返回上级分类ID，以及分类路径
 */
function nameArticleAndId($articleArray){
		$CataLog = new CataLog();
		$nameArray = $CataLog->lookRoleModule($articleArray['classid']);
		$dir_path = nameClassAndId($nameArray);
		return $dir_path;
}

/**
 *返回上级分类
 */
 function nameClassArry($topic,$str=''){
	if(empty($str)){
		$str[$topic['id']] = $topic;
		$str[$topic['id']]['menu'] = nameClassAndId($topic);
	}
	if(0 != $topic['pid']){
		$CataLog = new CataLog();
		$nameClassArray = $CataLog->lookRoleModule($topic['pid']);
		$str[$nameClassArray['id']] = $nameClassArray;
		$str[$nameClassArray['id']]['menu'] = nameClassAndId($nameClassArray);
		return nameClassArry($nameClassArray,$str);
	}else{
		$str[$topic['id']] = $topic;
		$str[$topic['id']]['menu'] = nameClassAndId($topic);
		array_multisort($str, SORT_ASC);
		return $str;
	}
 }
///**
// *返回下级分类ID，以及分类路径
// */
//function nameClassAndIdDown($topic,$sid='',$data=''){
//			$CataLog = new CataLog();
//			$nameClassArray = $CataLog->Rolefzid ($topic['id']);
//			return $nameClassArray;
//}

/*获得对应群组Tree*/
function getRoleTree($data,$roleid) {
	global $config,$userInfo;
	if(empty($userInfo['role'])){
		$role = new Role();
		$roleIdTreeArray = $role->seachRole($roleid);
	}else{
		$roleIdTreeArray = $userInfo;
		$roleIdTreeArray['role'] = explode("|", $roleIdTreeArray['role']);
	}
	foreach ($data as $key=>&$value){
		$bool = RoleUser($value['id'],$roleIdTreeArray['role']);
		if(!empty($bool)) {
			$newData[] =  $value;
		}
	}
	unset($data);
	return $newData;
}

//// 获得最在深度
function getTree($data,$roleid,$hide = 0) {
    if(empty($hide)) {
	    $tree = getCache(MENU_TREE,$roleid);
    }else{
	    $tree = getCache(MENU_TREE,$roleid.'_show');
    }
	if(empty($tree)) {
		$data = getRoleTree($data,$roleid);
		$depth = 0;
		if(!is_array($data)) {
			return 0;
		}
		foreach ($data AS $k => &$v) {
			if ($v['depth'] > $depth){
				$depth = $v['depth'];
			}
			$v['attributes']['file'] = $v['file'];
			$v['attributes']['action'] = $v['action'];
		}
		$tree = getC($data, $depth);
        if(empty($hide)) {
            setCache(MENU_TREE,$roleid,$tree);
        }else{
            setCache(MENU_TREE,$roleid.'_show',$tree);
        }
	}
	return $tree;
}



//// 获得最编辑权限树
function getEditTree($data,$gid=0) {
	if(!empty($gid)){
		$tree = getCache(CATALOG,$gid);
	}
	if(empty($tree)) {
		if(!empty($gid)){
			$data = getEditRoleTree($data,$gid);
		}
			$depth = 0;
			if(!is_array($data)) {
				return 0;
			}
			foreach ($data AS $k => &$v) {
				if ($v['depth'] > $depth){
					$depth = $v['depth'];
				}
			}
			$tree = getC($data, $depth);
		if(!empty($gid)){
			setCache(CATALOG,$gid,$tree);
		}
	}
	return $tree;
}

/*获得对应群组Tree*/
function getEditRoleTree($data,$gid) {
	$catalog = new Catalog();
	//获取用户可编辑栏目
	$roleIdTreeArray = $catalog->seachUserEditRole($gid);
	foreach ($data as $key=>&$value){
		$bool = RoleUser($value['id'],$roleIdTreeArray['role']);
		if(!empty($bool)) {
			$newData[] =  $value;
		}
	}
	unset($data);
	return $newData;
}

//检查某个权限是否这个用户具有
function RoleUser($roleId,$roleArray) {
	if(is_array($roleArray)) {
		$key = array_search($roleId,$roleArray);
		if(FALSE === $key){
			return 0;
		}
		return 1;
	}
}

function getC($array, $depth) {
    for ($i=$depth; $i>=0; --$i) {
        if ($arr) {
            $s = $arr;
            unset($arr);
            foreach ($array AS $k => $v) {
                if ($v['depth'] == $i) {
                    foreach ($s AS $key => $val) {
                        if ($v['id'] == $val['pid']) {
                            $ss[] = $val;
                        }
                    }
                    $v['children'] = $ss;
                    unset($ss);
                    $sss[] = $v;
                }
            }
            $arr = $sss;
            unset($sss);
        } else {
            foreach ($array AS $k => $v) {
                if ($v['depth'] == $i) {
                    if ($v['pid'] >= 0) {
                        $arr[] = $v;
                        unset($v);
                    }
                }
            }
        }
    }
    return $arr;
}
/*根据权限ID判断是否具有权限*/
function getRoleId($id,$roleid) {
	global $config,$userInfo;
	if(empty($userInfo['role'])){
		$role = new Role();
		$roleIdTreeArray = $role->seachRole($roleid);
	}else{
		$roleIdTreeArray = $userInfo;
		$roleIdTreeArray['role'] = explode("|", $roleIdTreeArray['role']);
	}
	$bool = RoleUser($id,$roleIdTreeArray['role']);
	return $bool;
}

//开启报错
function errorFunction($error) {
	if($error) {
		ini_set("display_errors", "On");
	}else{
		error_reporting(E_ALL);
		ini_set("display_errors", "Off");
	}
}
errorFunction(SHOW_ERROR);

class ArrayToXML
{
	/**
	 * The main function for converting to an XML document.
	 * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
	 *
	 * @param array $data
	 * @param string $rootNodeName - what you want the root node to be - defaultsto data.
	 * @param SimpleXMLElement $xml - should only be used recursively
	 * @return string XML
	 */
	public static function toXml($data, $rootNodeName = 'data', $xml=null)
	{
		// turn off compatibility mode as simple xml throws a wobbly if you don't.
		if (ini_get('zend.ze1_compatibility_mode') == 1)
		{
			ini_set ('zend.ze1_compatibility_mode', 0);
		}

		if ($xml == null)
		{
			$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
		}

		// loop through the data passed in.
		foreach($data as $key => $value)
		{
			// no numeric keys in our xml please!
			if (is_numeric($key))
			{
				// make string key...
				$key = "unknownNode_". (string) $key;
			}

			// replace anything not alpha numeric
			$key = preg_replace('/[^a-z]/i', '', $key);

			// if there is another array found recrusively call this function
			if (is_array($value))
			{
				$node = $xml->addChild($key);
				// recrusive call.
				ArrayToXML::toXml($value, $rootNodeName, $node);
			}
			else
			{
				// add single node.
                                $value = htmlentities($value);
				$xml->addChild($key,$value);
			}

		}
		// pass back as string. or simple xml object if you want!
		return $xml->asXML();
	}
}

/**
 * URL重定向
 *
 * @param string 	$url	要定向的URL地址
 * @param integer 	$time	定向的延迟时间，单位为秒
 * @param string 	$msg	提示信息
 */
function redirect($url,$time=0,$msg=''){
	//多行URL地址支持
	$url = str_replace(array("\n", "\r"), '', $url);
	include template('message');
	exit;
}

function valance($data,$msg) {
	if(empty($data)) {
		$message = array(
			'status' => 'error',
			'msg' => $msg,
		);
		echo json_encode($message);
		exit;
	}
	if( -1 == $data) {
		$message = array(
			'status' => 'error',
			'msg' => $msg,
		);
		echo json_encode($message);
		exit;
	}
}

/**
 * 创建目录
 * @param string $base_dir 目录基路径 结构为256*256
 * @param string $key 关键值
 * @param string $type  选择是何种类型的路径, 默认'num' 是数字, 其它如 'str'是字母之类
 * @return string
 */
function get_path($base_dir, $key, $type = 'num')
{

	if ($type == 'num')	// 按数字方式
	{
		$tmp = floor($key / 90000);
		$tmp2 = $key - $tmp * 90000;
		settype($tmp, 'string');
		$dir1 = '';
		$dir1 .= $tmp . '/';
		$tmp = floor( $tmp2 / 300);
		settype($tmp, 'string');
		$dir1 .= $tmp . '/';
		$dir1 .= $key ;

		if (!$base_dir || !$dir1)
		{
			return false;
		}

		if ( (!is_dir($base_dir)) && (!mkdir($base_dir, 0777)) )
		{
			if (!mkdir($base_dir))
			{
				return false;
			}
		}

		$dir = explode('/', $dir1);

		foreach($dir as $k => $v)
		{
			$base_dir .= '/' . $v;
			if ( (!is_dir($base_dir)) && (!mkdir($base_dir)) )
			{
				return false;
			}
		}

		return $dir1."/";
	}
	else	// 按字符串方式
	{
		$m = md5($key);
		$d = $m{0} . $m{3} . "/" . $m{1} . $m{2};
		if ($base_dir && !is_dir($base_dir . "/" . $d))
		{
			@mkdir($base_dir . "/" . $d);
		}


		return $d . "/";
	}
}

/**
 * 创建目录
 *
 * @param 目录地址 $dir
 * @param 创建权限 $mode
 * @return bool
 */
function mk_dir($dir, $mode = 0755){
  if ( is_dir($dir)||@mkdir($dir,$mode) ){
  	return true;
  }
  if ( !mk_dir(dirname($dir),$mode) ){
  	return false;
  }
  return @mkdir($dir,$mode);
}

/**
 * 获取客户端IP地址
 *
 * @return string
 */
function get_client_ip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}



/**
 *输出无缓存头
 *
 * @param string	 $comments
 * @return string
 */
function header_no_cache()
{
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	header("Cache-Control: no-cache, must-revalidate");
	header("Pragma: no-cache");
}


/**
 *判断是否是IE
 *  @return  bool
 *
 */
function is_ie() {
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if ((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
	if (strpos($useragent, 'msie ') !== false) return true;
	return false;
}


/**
 *判断文件后缀
 *@返回文件后缀
 * return bool
 */
function file_ext($filename) {
	$pathinfo = pathinfo($filename);
	return strtolower($pathinfo['extension']);
}


/**
 *下载文件输出头
 *@return 1;
 */
function file_down($filepath, $filename = '') {
	$filename or $filename = basename($filepath);
	is_ie() && $filename = rawurlencode($filename);
	$filetype = file_ext($filename);
	$filesize = sprintf("%u", filesize($filepath));
	if (ob_get_length() !== false) @ob_end_clean();
	header('Pragma: public');
	header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Cache-Control: pre-check=0, post-check=0, max-age=0');
	header('Content-Transfer-Encoding: binary');
	header('Content-Encoding: none');
	header('Content-type: ' . $filetype);
	header('Content-Disposition: attachment; filename="' . $filename . '"');
	header('Content-length: ' . $filesize);
	readfile($filepath);
	exit;
}

/**
 * 转换Mysql的DATETIME格式到需要的格式
 *
 * @param string $time
 * @param string $fmt
 * @return string
 */
function toFmtDate($time, $fmt)
{
	$temp = strtotime($time);
	return date($fmt, $temp);
}


//获取特定区域的HTML GetHtmlArea('yingying', '<title>yingying</title>', $myResultStr, 0)
function GetHtmlArea($sptag,$areaRule,$html,$regex=1){
  //用正则表达式的模式匹配
  if($regex)
  {
	 $areaRule = str_replace("/","\\/",$areaRule);
	 $areaRules = explode($sptag,$areaRule);
	 $arr = array();
	 if($html==''||$areaRules[0]==''){ return ''; }
   preg_match('/'.$areaRules[0]."(.*)".$areaRules[1]."/isU",$html,$arr);
   if(!empty($arr[1])){ return trim($arr[1]); }
   else{ return ''; }
  }
  //用字符串模式匹配
  else
  {
	 $areaRules = explode($sptag,$areaRule);
	 if($html=='' || $areaRules[0]==''){ return ''; }
	 $posstart = @strpos($html,$areaRules[0]);
	 if($posstart===false){ return ''; }
	 $posend = @strpos($html,$areaRules[1],$posstart);
	 if($posend > $posstart && $posend!==false)
		 return str_replace('\\','',str_replace("'",'"',substr($html,$posstart+strlen($areaRules[0]),$posend-$posstart-strlen($areaRules[0]))));
	 else
		 return '';
  }
}




/**
 * 创建多级目录
 *
 * @param string	 $comments
 * @return string
 */
function makedir($dir, $mode = 0777) {
	if (!$dir)
		return 0;
	$dir = str_replace("\\", "/", $dir);
	$dir = str_replace("//", "/", $dir);
	$mdir = "";
	foreach (explode("/", $dir) as $val) {
		$mdir .= $val . "/";
		if ($val == ".." || $val == ".")
			continue;
		if (!file_exists($mdir)) {
			if (!@ mkdir($mdir, $mode)) {
				echo "创建目录 [" . $mdir . "]失败.";
				exit;
			}
		}
	}
	return true;
}





/**
 * 读取参数
 *
 * @param string		$name
 * @param string		$type
 * @return mixed
 */
function _g($name){
	if ( isset($_GET[$name]) ){
		$ret = $_GET[$name];
	}
	else if ( isset($_POST[$name]) ){
		$ret = $_POST[$name];
	}
	else if ( isset($_REQUEST[$name]) ){
		$ret = $_REQUEST[$name];
	}
	else{
		$ret = false;
	}
	return $ret;
}

/**
 * 权限判断函数
 *
 * @param string	 $comments
 * @return string
 */
function Role($_do,$userInfo) {
	$url = $_SERVER['PHP_SELF'];
	$filename = end(explode('/',$url));
	$op = trim(_g($_do));
	$Role = new Role();
	$RoleX = $Role->RoleX($filename,$op,$_do,$userInfo);
	if(empty($RoleX)) {
		include template("Role.html");
		exit;
	}
    return $RoleX;
}



/**
 *判断是否具有权限
 */
function Cheacked($id,$arrayData) {
	$k = array_search($id,$arrayData);
	if(FALSE === $k){
	}else{
		echo 'checked';
	}
}

/**
 +----------------------------------------------------------
 * 根据给定的字符串生成图像
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $string  字符串
 * @param string $size  图像大小 width,height 或者 array(width,height)
 * @param string $font  字体信息 fontface,fontsize 或者 array(fontface,fontsize)
 * @param string $type 图像格式 默认PNG
 * @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
 * @param bool $border  是否加边框 array(color)
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function buildString($string,$rgb=array(),$filename='',$type='png',$disturb=1,$border=true) {
		if(is_string($size))		$size	=	explode(',',$size);
		$width	=	$size[0];
		$height	=	$size[1];
		if(is_string($font))		$font	=	explode(',',$font);
		$fontface	=	$font[0];
		$fontsize	 	=	$font[1];
		$length		=	strlen($string);
		$width = ($length*9+10)>$width?$length*9+10:$width;
		$height	=	22;
		if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
			$im = @imagecreatetruecolor($width,$height);
		}else {
			$im = @imagecreate($width,$height);
		}
		if(empty($rgb)) {
			$color = imagecolorallocate($im, 102, 104, 104);
		}else{
			$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
		}
		$backColor = imagecolorallocate($im, 255,255,255);    //背景色（随机）
		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
		$pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色

		@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
		@imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
		@imagestring($im, 5, 5, 3, $string, $color);
		if(!empty($disturb)) {
			// 添加干扰
			if($disturb=1 || $disturb=3) {
				for($i=0;$i<25;$i++){
					imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
				}
			}elseif($disturb=2 || $disturb=3){
				for($i=0;$i<10;$i++){
					imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$pointColor);
				}
			}
		}
		output($im,$type,$filename);
}
function output($im,$type='png',$filename=''){
	header("Content-type: image/".$type);
	$ImageFun='image'.$type;
	if(empty($filename)) {
		$ImageFun($im);
	}else{
		$ImageFun($im,$filename);
	}
	imagedestroy($im);
}


/**
 *返回用户信息
 *@如果存在返回userInfo信息
 */
function userInfo() {
    $cookie = Cookie::getInstance();
    $username = $cookie->get('username');
    $password =$cookie->get('password');
    $email =$cookie->get('email');
	$uid = $cookie->get('uid');
    $user = new User();
    $userInfo = $user->getUserInfo($uid);
    if($userInfo['email'] === $email && $userInfo['username'] === $username && $userInfo) {
        return $userInfo;
    }else{
        return 0;
    }
}


/***
 *edu24调用
 */
function edu24($Id){
	global $config,$_G,$db;
	$data = getCache(EDU24,'edu24'.'-'.$Id,1);
	if(empty($data)) {
		$eduClass = new edu24();
		$lesson_type_code= $eduClass->getRowType($Id);
		if(empty($lesson_type_code)){
			exit;
		}
		$dataArray[$lesson_type_code['lesson_type_code']] = $lesson_type_code;
		$dataArray[$lesson_type_code['lesson_type_code']]['class'] = getGad($Id);
		foreach($dataArray[$lesson_type_code['lesson_type_code']]['class'] as $pp=>$jj){
			$num += $jj['count'];
		}
		$dataArray[$lesson_type_code['lesson_type_code']]['lesson_class_num'] = $num;
		setCache(EDU24,'edu24'.'-'.$Id,$dataArray,1);
		return $dataArray;
	}
	return $data;
}

function getGad($Id){
	$xmlData	= edu24::getGad($Id);
	if(is_array($xmlData['lesson'])){
		foreach($xmlData['lesson'] as $k=>&$n){
			if(empty($n['class']['class_code'])){
				foreach($n['class'] as $kk=>&$nn){
					$rr = edu24::getJ($nn['class_code']);
					$nn['relate_sum'] = count($rr['relate']);
					if(is_array($rr['relate'])){
						$leraning = 0;
						if(empty($rr['relate']['relate_num'])){
								foreach($rr['relate'] as $kkk=>&$nnn){
									if(!is_array($nnn['listen_address'])){
										$leraning = 1;
									}
								}
						}else{
							if(!is_array($rr['relate']['listen_address'])){
								$leraning = 1;
							}
						}
					}
					if($leraning !=1){
						unset($n['class'][$kk]);
					}
					if(empty($nn['relate_sum'])){
						unset($n['class'][$kk]);
					}
				}
				$n['count'] = count($n['class']);
			}else{
				$rr = edu24::getJ($n['class']['class_code']);
				
				if(empty($rr['relate']['relate_num'])){
					$n['class']['relate_sum'] = count($rr['relate']);
					foreach($rr['relate'] as $kkk=>&$nnn){
						if(!is_array($nnn['listen_address'])){
							$leraning = 1;
						}
					}
				}else{
					$n['class']['relate_sum'] = 1;
					if(!is_array($rr['relate']['listen_address'])){
						$leraning = 1;
					}
				}
				
				if($leraning !=1){
					unset($n['class'][$kk]);
				}



				if(empty($n['class']['relate_sum'])){
					unset($n);
				}else{	
					$n['count'] = 1;
				}

			}
			$xmlDataX[$k] = $n;
		}
	}
	return $xmlDataX;
}
//栏目页使用
function getCommentArray($classid,$num,$page){
	global $config,$_G;
	$Catalog = new Catalog();
	$topic = $Catalog->lookRoleModule($classid);
	$edu24 = explode(',',$topic['edu24']);
	if(empty($topic)){
		exit;
	}
	$title = $topic['text'];
	$str = nameClassAndId($topic);
	switch($topic){
		case 2==$topic['ispart']:
			//$dataArry = getCateGory($classid,$num,'','','id','-','',$page);
			$dirPath = DIR_ROOT.$str.'/index.html';
			include template($topic['tempindex']);
		break;
		case 1==$topic['ispart']:
			$findkey = '`classid` = '.$classid;
			$numRs = $Catalog->getArctnewCount($findkey);
			$p = new pagination();
			$url = CREATEHTML ? nameClassAndId($topic) :'column.php';


			$p->set($numRs,$num,$url,false,'1');
			if(1==$page){
				$dirPath = DIR_ROOT.$str.'index.html';
			}else{
				$dirPath = DIR_ROOT.$str.'/list-'.$page.'.html';
			}
			include template($topic['templist']);
		break;
	}
	if(CREATEHTML) {
		mk_dir(DIR_ROOT.$str);
		createhtml($dirPath);
		if(1==$topic['ispart']){
			copy(DIR_ROOT.$str.'index.html',DIR_ROOT.$str.'/list-1.html');
		}
	}
}



/**
 * @package     二维数组排序
 * @version     $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $
 *
 *
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * sysSortArray($Array,&quot;Key1&quot;,&quot;SORT_ASC&quot;,&quot;SORT_RETULAR&quot;,&quot;Key2&quot;……)
 * @author                      Chunsheng Wang &lt;wwccss@263.net>
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by(&quot;SORT_ASC&quot;|&quot;SORT_DESC&quot;)
 * @param  string  $SortType1   the sort type(&quot;SORT_REGULAR&quot;|&quot;SORT_NUMERIC&quot;|&quot;SORT_STRING&quot;)
 * @return array                sorted array.
 */
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }

    // Get args number.
    $ArgCount = func_num_args();

    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I < $ArgCount;$I ++)
    {
        $Arg = func_get_arg($I);
        if(!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }

    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }

    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}


//栏目生成函数
function lanHtml($value){
	global $config;
	switch($value['ispart']){
		case 2 == $value['ispart']:
			$url = $config['webUrl'].'column.php?classid='.$value['id'];
			openurl($url);
		break;
		case 1 == $value['ispart']:
			$Catalog = new Catalog();
			$findkey = '`classid` = '.$value['id'];
			$numRs = $Catalog->getArctnewCount($findkey);
			$nums = ceil($numRs/$config['num']);
			for ($i = 1; $i <= $nums; $i++){
				$url = $config['webUrl'].'column.php?classid='.$value['id'].'&page='.$i;
				openurl($url);
			}
		break;
	}
}

function indexHtml(){
	$url = $config['webUrl'].'index.php';
	openurl($url);
}
?>